<template>
	<view>
		<!-- 输入框 -->
		<view class="bgw">
			<view class="input_box">
				<image src="https://mg-print.oss-cn-shenzhen.aliyuncs.com/img/search.png" mode=""></image>
				<input v-model="searchName" type="text" placeholder="输入文件名" />
				<button class="search_button" @click="search">搜索</button>
			</view>
			<!-- 筛选项 -->
			<view class="screen">
				<view class="screen_item" v-for="(item, index) in screenList" :key="index" @click="select(index)">
					<text :class="item.isSelect ? 'tag_select' : ''">{{ item.text }}</text>
					<image class="arr_release"
						:src="item.isSelect ? `https://mg-print.oss-cn-shenzhen.aliyuncs.com/img/tag_act.png` : `https://mg-print.oss-cn-shenzhen.aliyuncs.com/img/tag_not.png`"
						mode=""></image>
				</view>
			</view>
			<!-- 下拉项目 -->
			<view class="choose_list" v-if="showChoose">
				<view class="choose_item" v-for="(item, index) in chooseList" @click="changeText(index)" :key="index">
					<text :class="[item.isSelect ? 'is_select' : false]"> {{ item.text }}</text>
				</view>
			</view>
		</view>
		<!-- 文库列表 -->
		<view class="library_list">
			<block v-if="libraryList.length > 0">
				<view class="library_container" v-for="(item, index) in libraryList" :key="index">
					<view class="library_item">
						<view class="img_box" @click="toPreView(item)">
							<image :src="item.ImageUrl" mode="aspectFill"></image>
						</view>
						<view class="info">
							<text>{{ item.LibraryName }}</text>
							<view class="source">{{ item.LibraryName }}</view>
							<view class="numsInfo">
								<view>
									<image src="https://mg-print.oss-cn-shenzhen.aliyuncs.com/img/watch.png"></image>
									<text>{{ item.NumberViews }}</text>
								</view>
								<view>
									<image src="https://mg-print.oss-cn-shenzhen.aliyuncs.com/img/print.png"></image>
									<text>{{ item.NumberDownloads }}</text>
								</view>
								<view>
									<text>共{{ item.TotalingPages || 1 }}页</text>
								</view>
							</view>
							<view class="bottom">
								<view class="price">
									<view class="price_text">
										<text class="symbol" v-if="item.Price > 0">￥</text>
										{{ item.Price == 0 ? '免费' : `${item.Price}` }}
									</view>
								</view>
								<view class="bottom_box">
									<view v-if="!item.IsCollect" class="collect" @click="collectOrCancel(item)">
										收藏
									</view>
									<view v-if="item.IsCollect" class="is_collect" @click="collectOrCancel(item)">
										已收藏
									</view>
									<view class="print" @click="toPrint(item)">
										{{ item.IsPurchase || item.Price == 0 ? '打印' : `购买` }}
									</view>
								</view>
							</view>
						</view>

					</view>

				</view>
			</block>

			<pageEmpty v-if="libraryList.length == 0"></pageEmpty>

		</view>
		<!-- 点击分类弹出层 -->
		<u-popup :show="show" :round="10" mode="bottom" @close="close" @open="open" closeable closeIconPos="top-left"
			:closeOnClickOverlay="true">
			<view class="poup_container">
				<view class="title">
					<text>文库分类</text>
				</view>
				<u-tabs keyName="LcName" :activeStyle="{ color: '#3572FE', transform: 'scale(1.05)' }" :list="tabList"
					@click="clickTab"></u-tabs>
				<!-- 选项 -->
				<view class="option_list">
					<view :class="['option_item', item.isSelect ? 'option_select' : '']"
						@click="changeClassification(index, item.SubclassName, item)" v-for="(item, index) in optionList "
						:key="index">
						{{ item.SubclassName }}
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import pageEmpty from '@/components/pageEmpty/pageEmpty'
export default {
	components: {
		pageEmpty
	},
	data() {
		return {
			currentIndex: 0,
			showChoose: false,
			searchName: '',
			chooseList: [],
			libraryList: [],
			screenList: [{
				text: '分类',
				type: 0,
				isSelect: false
			},
			{
				text: '全部',
				type: 1,
				isSelect: false,
				childList: [{
					text: '全部'
				}, {
					text: '已收藏'
				}]
			},
			{
				text: '不限',
				type: 2,
				isSelect: false,
				childList: [{
					text: '不限'
				},
				{
					text: '付费'
				}, {
					text: '免费'
				},
				]
			},
			{
				text: '不限',
				type: 3,
				isSelect: false,
				childList: [{
					text: '不限'
				}, {
					text: '已购买'
				}, {
					text: '未购买'
				}]
			},

			],
			show: false,
			tabList: [],
			optionList: [],
			PageIndex: 1,
			PageSize: 10,
			SubclassCode: '',
			isThrottled: false,
		}

	},
	methods: {
		// 收藏或取消
		async collectOrCancel(item) {
			console.log(item);
			let res = await this.$api.post('Library/SetLibraryCollect', {
				LibraryCode: item.LibraryCode,
				IsCollect: !item.IsCollect
			})
			item.IsCollect = !item.IsCollect
			console.log(res);
		},
		async toPrint(item) {
			if (item.Price == 0 || item.IsPurchase) {
				// 跳转首页，存储到stroge里面，然后上传文件
				uni.setStorageSync('uploadOption', {
					name: item.LibraryName,
					url: item.LibraryUrl
				})
				// uni.switchTab({
				// 	url: `/pages/tab/home`
				// })
				this.$api.post('Library/SetFileLibraryD', {
					LibraryCode: item.LibraryCode
				})
				this.nav_to('/pages/otherPage/uploadFileList?isLibrary=true')
				
			} else {
				if (this.isThrottled) {
					return; // 如果在节流时间内，直接返回
				}
				this.isThrottled = true; // 设置为正在执行

				setTimeout(() => {
					this.isThrottled = false; // 重置为可以执行
				}, 3000); // 设置节流时间为 3 秒

				try {
					let res = await this.$api.post('Order/SetOpenMembership', {
						LibraryCode: item.LibraryCode,
						Delivery_Province: '',
						Delivery_City: '',
						Price: item.Price,
					});

					let pres = await this.$api.post('/Payment/PayV2', {
						body: res.data.EventType,
						EventType: res.data.EventType,
						EventID: res.data.EventID,
						CompanyID: 7006,
						SourcePage: '/pages/tab/home',
					});

					let _this = this;
					console.log(pres);
					let payObj = JSON.parse(pres.data);

					uni.requestPayment({
						provider: 'wxpay',
						// #ifdef APP
						orderInfo: payObj,
						// #endif
						// #ifdef MP-WEIXIN
						timeStamp: payObj.timeStamp,
						nonceStr: payObj.nonceStr,
						package: payObj.package,
						signType: payObj.signType,
						paySign: payObj.paySign,
						// #endif
						success: async function (res) {
							_this.$pv.msg('购买成功，可在“我的文库”下查看模版');
							console.log(res);
							setTimeout(() => {
								// _this.closeAlert()
								// _this.upDateInfo();
							}, 500);
							item.IsPurchase = true;
							// _this.nav_back(2000);
						},
						fail: function (err) {
							console.log(err);
							_this.$pv.msg('您已取消支付');
							console.log(_this.uploadFileList);
						}
					});
				} catch (error) {
					console.error('支付过程出错:', error);
					this.$pv.msg('支付失败，请重试');
				}
			}


		},
		toPreView(item) {
			let that = this
			uni.showLoading({
				title: `正在打开文件`
			})
			uni.downloadFile({
				url: item.LibraryUrl,
				success: function (res) {
					var filePath = res.tempFilePath;
					uni.openDocument({
						filePath: filePath,
						showMenu: true,
						success: async function (res) {
							let result = await that.$api.post('Library/SetFileLibraryV', {
								LibraryCode: item.LibraryCode
							})
							console.log('打开文档成功');
							console.log(result);
							item.NumberViews++
							uni.hideLoading()
						}
					});
				}
			});
		},
		changeClassification(index, text, item) {
			// 取消所有选项和屏幕列表项的选择状态
			this.optionList.forEach(opt => opt.isSelect = false);
			this.screenList.forEach(screenItem => screenItem.isSelect = false);

			const selectedOption = this.optionList[index];
			selectedOption.isSelect = true;

			// 更新屏幕文本
			this.screenList[0].text = (selectedOption.SubclassCode === this.SubclassCode) ? "分类" : text;

			// 更新 SubclassCode
			if (selectedOption.SubclassCode === this.SubclassCode) {
				selectedOption.isSelect = false;
				this.SubclassCode = '';
			} else {
				this.SubclassCode = selectedOption.SubclassCode;
			}

			// 隐藏显示并重置状态
			this.show = false;
			this.libraryList = [];
			this.PageIndex = 1;

			// 获取新列表
			this.getList();

			// 调试信息（可选）
			// console.log(item);
		},



		// 弹窗关闭
		close() {
			this.show = false
			this.screenList[0].isSelect = false
		},
		// 弹窗打开
		open() {

		},
		// 修改分类text
		changeText(index) {
			// 修改text
			this.screenList[this.currentIndex].text = this.screenList[this.currentIndex].childList[index].text
			// 清空所有选中状态
			this.screenList[this.currentIndex].childList.forEach((item) => {
				item.isSelect = false;
			});
			this.screenList[this.currentIndex].childList[index].isSelect = true
			this.showChoose = false
			// 清空所有选中状态
			this.screenList.forEach((item) => {
				item.isSelect = false;
			});
			// console.log(JSON.stringify(this.screenList));
			this.libraryList = []
			this.PageIndex = 1
			this.getList()
		},
		search() {
			this.libraryList = []
			this.PageIndex = 1
			this.getList()
		},
		// 点击筛选
		select(index) {
			// 排他
			this.screenList.forEach((item) => {
				item.isSelect = false;
			});

			// 确保 index 在有效范围内
			if (index < 0 || index >= this.screenList.length) {
				console.error("Index out of bounds");
				return;
			}

			this.screenList[index].isSelect = true;

			// 使用多个 case 标签
			switch (index) {
				case 0:
					this.show = true;
					this.showChoose = false;
					break;
				case 1:
				case 2:
				case 3:
					if (this.screenList[index] && this.screenList[index].childList) {
						this.chooseList = this.screenList[index].childList;
					} else {
						this.chooseList = [];
					}
					this.showChoose = !this.showChoose;
					this.screenList[index].isSelect = this.showChoose
					this.currentIndex = index
					// 代码块2
					break;
				default:
					// 可选的 default 处理
					break;
			}

		},

		// 点击tab栏
		clickTab(e) {
			this.optionList = e.List
			console.log(e);
		},
		async getList() {
			const result = [];
			this.screenList.forEach(item => {
				if (item.text !== "分类" && item.childList) {
					item.childList.some(child => {
						if (item.type === 1) {
							if (child.text === "已收藏") {
								result.IsCollect = child.isSelect;
								return true;
							}
						}
						return false;
					});
				}
			});
			console.log(result);

			this.screenList.forEach((item) => {
				if (item.type == 2) {
					if (item.text == '不限') {
						result.IsPrice = ''
					}
					if (item.text == '付费') {
						result.IsPrice = true
					}
					if (item.text == '免费') {
						result.IsPrice = false
					}
				}
				if (item.type === 3) {
					console.log(item);
					console.log(item.text);
					if (item.text === "已购买") {
						result.IsPay = true;

					}
					if (item.text === "不限") {
						result.IsPay = '';
						console.log(result.IsPay);

					}
					if (item.text === "未购买") {
						result.IsPay = false;

					}
				}
			})
			let res = await this.$api.post('Library/GetFileLibrary', {
				LibraryName: this.searchName,
				SubclassCode: this.SubclassCode,
				PageIndex: this.PageIndex,
				PageSize: this.PageSize,
				IsPrice: result.IsPrice,
				IsCollect: result.IsCollect ? result.IsCollect : false,
				IsPay: result.IsPay,
			})
			console.log(res);
			this.libraryList = [...this.libraryList, ...res.data.LbData]
		},
		async getTypeList() {
			let res = await this.$api.post('Library/GetLcsList')
			this.tabList = res.data
			this.optionList = this.tabList[0].List

		}
	},
	onLoad() {
		this.getList()
		this.getTypeList()
	},
	onReachBottom() {
		this.PageIndex = this.PageIndex + 1
		this.getList()
	}
}
</script>

<style>
page {
	background-color: #f6f6f6;
}
</style>

<style lang="scss" scoped>
.symbol {
	font-weight: bold;
	font-size: 24rpx;
	color: #FF4B4B;
}

.bottom_box {
	display: flex;
	align-items: center;
	// margin-top: 30rpx;
	justify-content: flex-end;

	view {
		padding: 2rpx 24rpx;
		height: 48rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.collect {
		border-radius: 8rpx;
		border: 2rpx solid #3572FE;
		color: #3572FE;
		margin-right: 20rpx;
		font-size: 24rpx;
	}

	.is_collect {
		border-radius: 8rpx;
		border: 2rpx solid #D2D2D2;
		color: #333333;
		margin-right: 20rpx;
		font-size: 24rpx;
	}

	.print {
		background: #3572FE;
		border-radius: 8rpx;
		color: #FFFFFF;
		font-size: 24rpx;
	}
}

.is_select {
	color: #3572FE;
}

.choose_item {
	border-bottom: 1rpx solid #e8e8e8;
	height: 90rpx;
	display: flex;
	align-items: center;
	box-sizing: border-box;
	padding-left: 30rpx;
	background-color: #fff;
}

.choose_list {
	position: absolute;
	width: 100%;
	border: 1rpx solid #e8e8e8;
	border-bottom: none;
}

.bgw {
	background-color: #fff;
	padding-top: 24rpx;
	position: sticky;
	top: 0;
}

.price_text {
	font-weight: bold;
	font-size: 36rpx;
	color: #FF4B4B;
}

.bottom {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.tag_select {
	color: #3572FE;
}

.option_list {
	display: flex;
	flex-wrap: wrap;

	.option_item {
		height: 80rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 20rpx 30rpx;
		margin: 20rpx;
		background-color: #f3f3f3;
		border-radius: 40rpx;
		font-size: 24rpx;
	}

	.option_select {
		background-color: #fff;
		color: #3572FE;
		border: 1rpx solid #3572FE;
		;
	}
}

.poup_container {
	// height: 400rpx;
	box-sizing: border-box;
	padding: 30rpx;
	position: relative;

	.title {
		text-align: center;
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 40rpx;
	}
}

.source {
	font-size: 24rpx;
	border-radius: 18rpx;
	border: 1rpx solid #3572FE;
	color: #3572FE;
	padding: 2rpx 16rpx;
	width: fit-content;
}

.library_list {
	width: 100%;
	box-sizing: border-box;
	padding: 24rpx;
	background-color: #f6f6f6;
	display: flex;
	flex-direction: column;
	min-height: 500rpx;

	.library_container {
		border-radius: 16rpx;
		background-color: #ffffff;
		padding: 16rpx;
		margin-bottom: 20rpx;
	}

	.library_item {
		// height: 268rpx;
		box-sizing: border-box;

		display: flex;
		justify-content: space-between;

		// align-items: flex-end;
		.img_box {
			width: 158rpx;
			height: 224rpx;
			border-radius: 10rpx;
			background-color: #f6f6f6;
			box-shadow: 0rpx 0rpx 16rpx 0rpx rgba(0, 0, 0, 0.1);
			border-radius: 8rpx;

			image {
				width: 100%;
				height: 100%;
			}
		}

		.info {
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			margin-left: 20rpx;
			// height: 170rpx;
			flex: 1;
			// margin-right: 100rpx;

			.numsInfo {
				display: flex;
				align-items: center;
				justify-content: space-between;
				font-size: 24rpx;
				color: #666666;
				padding-right: 100rpx;

				view {
					display: flex;
					align-items: center;

					image {
						width: 32rpx;
						height: 32rpx;
						margin-right: 8rpx;
					}
				}
			}
		}


	}
}

.screen {
	// width: 720rpx;
	margin: 0 auto;
	display: flex;
	justify-content: space-between;
	height: 100rpx;
	margin-top: 20rpx;
	align-items: center;
	background-color: #ffffff;

	.screen_item {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		border-right: 1rpx solid #e6e6e6;
		font-size: 24rpx;

		&:nth-last-child(1) {
			border-right: none;
		}

	}
}

.arr_release {
	width: 24rpx;
	height: 24rpx;
	// position: absolute;
	// bottom: 5rpx;
	// right: 50%;
	// margin: 0 auto;
	transition: 0.5s;
}

.expand {
	transform: rotate(-90deg);
}

.not_expand {
	transform: rotate(90deg);
}

.search_button {
	display: flex;
	align-items: center;
	justify-content: center;
	position: absolute;
	right: 8rpx;
	z-index: 5;
	width: 120rpx;
	height: 56rpx;
	background: #3572FE;
	border-radius: 36rpx;
	font-size: 28rpx;
	color: #FFFFFF;
}

.input_box {
	width: 700rpx;
	margin: 0 auto;
	height: 70rpx;
	background-color: #f6f6f6;
	position: relative;
	border-radius: 50rpx;
	box-sizing: border-box;
	padding: 20rpx 24rpx;
	display: flex;
	align-items: center;

	input {
		width: 460rpx;
	}

	image {
		width: 40rpx;
		height: 40rpx;
		margin-right: 20rpx;
	}
}
</style>